//
//  RegisterViewController.swift
//  Showing
//
//  Created by Ralf on 5/3/15.
//  Copyright (c) 2015 com.next.starlooking. All rights reserved.
//

import UIKit

class RegisterViewController: TableViewController
{
    var tfUserName: UITextField?
    var tfPassword: UITextField?

    override func viewDidLoad()
    {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

        self.title = "注册"

        self.tableView.registerNib(UINib(nibName: "RegisterViewLogoCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "LOGO")
        self.tableView.registerNib(UINib(nibName: "RegisterViewUserNameCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "USER_NAME")
        self.tableView.registerNib(UINib(nibName: "RegisterViewPasswordCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "PASSWORD")
        self.tableView.registerNib(UINib(nibName: "RegisterViewRegisterCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "REGISTER")

        self.initBackButton()
    }

    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated);
        MobClick.beginLogPageView("RegisterView")
    }

    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated);
        MobClick.endLogPageView("RegisterView")
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 4
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cell: UITableViewCell!

        switch indexPath.row
        {
        case 0:
            cell = tableView.dequeueReusableCellWithIdentifier("LOGO", forIndexPath: indexPath) 
        case 1:
            cell = tableView.dequeueReusableCellWithIdentifier("USER_NAME", forIndexPath: indexPath)
            self.tfUserName = cell.viewWithTag(20) as? UITextField
        case 2:
            cell = tableView.dequeueReusableCellWithIdentifier("PASSWORD", forIndexPath: indexPath)
            self.tfPassword = cell.viewWithTag(20) as? UITextField
        case 3:
            cell = tableView.dequeueReusableCellWithIdentifier("REGISTER", forIndexPath: indexPath) 
        default:
            cell = nil
        }
        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        var height: CGFloat
        let screenRect = UIScreen.mainScreen().bounds

        switch indexPath.row
        {
        case 0:
            height = screenRect.size.width / 2 //image
        case 3:
            height = 80 //register button
        case 4:
            height = 60
        default:
            height = 40
        }

        return height
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        if indexPath.row < 1 || indexPath.row > 2
        {
            self.view.endEditing(true)

            if indexPath.row == 3
            {
                let userName = tfUserName!.text
                let password = tfPassword!.text
                self.register(userName!, password: password!)
            }
        }
    }

    func register(userName: String, password: String)
    {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        self.view.endEditing(true)

        let rs = appDelegate.contactManager.registerWithUserName(userName, andPassword: password)

        if rs == nil
        {
            self.alertNetworkConnectionException()
            self.navigationController?.popToRootViewControllerAnimated(true)
        }
        else
        {
            if !rs.hasErrors() && !rs.isEmpty()
            {
                MobClick.event("RegisterLogin")

                self.alertSuccessMessage("注册成功")

                NSNotificationCenter.defaultCenter().postNotificationName("Refresh Shop2", object: nil)

                NSNotificationCenter.defaultCenter().postNotificationName("Login Successful", object: nil)
                
                
                let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                self.view.endEditing(true)
                appDelegate.contactManager.loginWithUserName(userName, andPassword: password)
                self.navigationController?.popToRootViewControllerAnimated(true)
            }
            else
            {
                self.alertErrorMessage(rs.errorMessage)
            }
        }

    }

}
